package com.mujin.keji.collectionsystem.module.outboundtask.views;

import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseFragment;
import com.mujin.keji.collectionsystem.db.database.AppDataBase;
import com.mujin.keji.collectionsystem.db.domain.VisitApplyMarkBean;
import com.mujin.keji.collectionsystem.listeners.CustomItemClickListener;
import com.mujin.keji.collectionsystem.module.outboundtask.adapter.CollectionRecordAdapter;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.BoundTaskDto;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.MarkDtoList;
import com.mujin.keji.collectionsystem.module.outboundtask.viewmodel.MarkViewModel;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.MarkVo;
import com.mujin.keji.collectionsystem.utils.DisplayUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 催收记录fragment碎片
 *
 * @author weishixiong
 * @Time 2018-03-21
 */

public class CollectionRecordsFragment extends BaseFragment implements CustomItemClickListener {
    private RecyclerView rvCollectionRecord;
    private LinearLayoutManager linearLayoutManager;
    private CollectionRecordAdapter collectionRecordAdapter;
    private MarkViewModel markViewModel;
    private int page;
    private static final int PAGE_SIZE = 20;
    private List<MarkDtoList> markDtoLists;
    private boolean isRefresh;//是否刷新
    private LinearLayout llNoData;
    private TextView tvNoData;
    private SmartRefreshLayout refreshLayout;
    private SmartRefreshLayout srNoData;


    @Override
    protected void loadData() {


    }

    @Override
    protected void createViewModel() {
        markViewModel = ViewModelProviders.of(this).get(MarkViewModel.class);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_collectionrecords;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        rvCollectionRecord = (RecyclerView) view.findViewById(R.id.rv_collection_record);
        llNoData = (LinearLayout) view.findViewById(R.id.ll_no_data);
        tvNoData = (TextView) view.findViewById(R.id.tv_no_data);
        refreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshLayout);


        srNoData = (SmartRefreshLayout) view.findViewById(R.id.sr_no_data);

        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);

        srNoData.setEnableRefresh(false);
        srNoData.setEnableLoadMore(false);

        srNoData.setHeaderHeight(DisplayUtil.dip2px(getActivity(), 16));
        refreshLayout.setHeaderHeight(DisplayUtil.dip2px(getActivity(), 16));

        refreshLayout.setEnableLoadMore(false);
        initCollectionView();
    }

    /**
     * 初始化催收记录列表记录
     */
    private void initCollectionView() {
        markDtoLists = new ArrayList<>();
        linearLayoutManager = new LinearLayoutManager(getActivity());
        rvCollectionRecord.setLayoutManager(linearLayoutManager);
        collectionRecordAdapter = new CollectionRecordAdapter(getActivity(), markDtoLists);
        rvCollectionRecord.setAdapter(collectionRecordAdapter);

    }

    @Override
    protected void initData() {
       // refreshLayout.autoRefresh();

        isRefresh = true;
        page = 1;
        loadMarkData();

    }

    /**
     * 加载催收记录数据
     */
    private void loadMarkData() {
        if (EmptyUtils.isNotEmpty(((CaseInformationActivity) getActivity()).getDto()))
        {
            BoundTaskDto dto = ((CaseInformationActivity) getActivity()).getDto();
            String caseId = dto.getCaseId();
            MarkVo vo = new MarkVo();
            String companyOrgSign = dto.getCompanyOrgSign();
            vo.setCurrentPage(page);
            vo.setCaseId(caseId);
            vo.setCompanyOrgSign(companyOrgSign);
            vo.setPageSize(PAGE_SIZE);
            vo.setApplyId(dto.getId());

            Flowable<VisitApplyMarkBean> flowable = AppDataBase.getInstance(getActivity()).getVisitDao().queryVisitMark(caseId);

            flowable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<VisitApplyMarkBean>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(1);
                        }

                        @Override
                        public void onNext(VisitApplyMarkBean visitApplyMarkBean) {
                            srNoData.finishRefresh();
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                            if (isRefresh) {
                                markDtoLists.clear();
                            }

                            String markBeanStr = visitApplyMarkBean.getMarkBeanStr();
                            List<MarkDtoList> marks = JSONArray.parseArray(markBeanStr, MarkDtoList.class);
                            //过滤注记类型
                            List<MarkDtoList> newMarks = new ArrayList<>();
                            for (MarkDtoList mark : marks) {
                                if (!"注记".equals(mark.getCollectType())) {
                                    newMarks.add(mark);
                                }
                            }
                            markDtoLists.addAll(newMarks);
                            collectionRecordAdapter.notifyDataSetChanged();

                        }

                        @Override
                        public void onError(Throwable t) {
                            srNoData.finishRefresh();
                            refreshLayout.finishRefresh();
                            ToastUtils.showToast(t.getMessage());
                        }

                        @Override
                        public void onComplete() {
                            srNoData.finishRefresh();
                            refreshLayout.finishRefresh();

                        }
                    });

        }
        else{
            srNoData.finishRefresh();
            refreshLayout.finishRefresh();
        }
    }

    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                page = 1;
                loadMarkData();
            }
        });
        srNoData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                page = 1;
                loadMarkData();
            }
        });

    }

    @Override
    public void onItemClick(View view, int position) {

    }
}
